<?php

namespace Admin\Library;

class Weixin
{
    /**
     * 获取access_token
     * @author tiedong
     * @date 2018-02-06
     */
    public static function getAccessToken()
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $accessToken = $redis->hGetAll('access_token');

        if (!$accessToken) {
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx88ef2e46f138b13f&secret=3b686fe119871859600aafe690a2670d';
            $html = file_get_contents($url);
            $output = json_decode($html, true);
            $accessToken = $output['access_token'];
            $redis->hMSet('access_token', $accessToken);
            $redis->setTimeout('access_token', 7200);
        }

        return $accessToken;
    }

    /**
     * 发送模板消息
     *
     * @param $openid
     * @param $templateId
     * @param $page
     * @param $formId
     * @param $data
     * @return mixed
     */
    public static function templateSend($openid, $templateId, $page, $formId, $data)
    {
        $accessToken = self::getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . $accessToken;
        foreach ($data as $key => $value) {
            $data[$key] = ['value' => $value];
        }
        $res = self::httpPost($url, json_encode([
            'touser'      => $openid,
            'template_id' => $templateId,
            'page'        => $page,  // 点击跳转页面
            'form_id'     => $formId,
            'data'        => $data,
        ]));
        return json_decode($res, true);
    }

    /**
     * http 请求
     * @param $url
     * @param null $data
     * @return mixed
     */
    private static function httpPost($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}